<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "lib/func.autoloader.php");

// Use the database settings defined in SimpleDBO.cfg
$sql = new SQL();

// Get a list of tables
$db_tables = $sql->Tables();

// Pull stuff from post
$tables = $_POST['tables'];
$folder = $_POST['folder'];

// Make sure the folder has a trailing slash
if($folder != "" && substr($folder, -1) != "/")
	$folder = $folder . "/";
else if($folder == "")
{
	$folder = (substr($_SERVER['DOCUMENT_ROOT'], -1) == "/") ? $_SERVER['DOCUMENT_ROOT'] . SIMPLEDBO_LIB_SUBPATH : $_SERVER['DOCUMENT_ROOT'] . "/" . SIMPLEDBO_LIB_SUBPATH;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/cb.css" />
<title>SimpleDBO Class Builder</title>

<script language="javascript">

function selectAll()
{
	var x      = 0;
	var tables = document.buildform.tables.options;
	for(var i = 0; i < tables.length; i++)
	{
		tables[i].selected = true;
	}
}

function selectNone()
{
	var x      = 0;
	var tables = document.buildform.tables.options;
	for(var i = 0; i < tables.length; i++)
	{
		tables[i].selected = false;
	}
}

</script>

</head>

<body>

<div align="center">
  <div id="container">
    <h1>SimpleDBO Class Builder</h1>
    <small>Connected to host <strong><?php echo $sql->host . ":" . $sql->db ?></strong> as <strong><?php echo $sql->user ?></strong>
    <form name="buildform" id="buildform" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
    
      <p><label for="tables">Select the tables to build class files for</label><br />
      <select id="tables" name="tables[]" size="10" multiple="multiple">
      <?php
        foreach($db_tables as $table)
        {
            $selected = (array_search($table, $tables) !== false) ? " selected=\"selected\"" : "";
            echo "    <option value=\"{$table}\"{$selected}>{$table}</option>\n";
        }
      ?>
      </select><br />
      <input type="button" value="Select All" onclick="selectAll();" /> 
      <input type="button" value="Select None" onclick="selectNone();" /></p>
      
      <p><label for="folder">Where should I save the files?</label><br />
        <input type="text" class="folder" name="folder" value="<?php echo stripslashes($folder) ?>" />
      </p>
      
      <input type="submit" value="Build" />
    </form>

<?php
// Did they submit everything?
if($folder != "" && count($tables) > 0)
{
	echo "<hr />";
	
	// First, load the template files
	$class = file_get_contents("templates/class.txt");
	$prop  = file_get_contents("templates/property.txt");
	
	// Start looping through the tables
	foreach($tables as $table)
	{
		// Figure out the class and filename
		$className = SIMPLEDBO_CLASSNAME_PREFIX . str_replace(" ", "", ucwords(str_replace("_", " ", $table)));
		$fileName  = SIMPLEDBO_CLASSFILENAME_PREFIX . $className . SIMPLEDBO_CLASSFILENAME_SUFFIX;
		$date      = date("F j, Y");
		
		echo "<p>Writing class <strong>{$className}</strong> to <strong>$fileName</strong>...";
		
		// Build the properties list
		$properties = array();
		$columns    = $sql->Columns($table);
		$longest    = 0;
		foreach($columns as $column)
		{
			// Get the column's description
			$desc = $sql->Describe($table, $column);
			
			echo "<!--"; print_r($desc); echo "-->";
		
			// Rip everything out
			$property = str_replace("#COLUMN NAME#", $column,             $prop);
			$property = str_replace("#TYPE#",        $desc['type'],       $property);
			$property = str_replace("#ATTRIBUTES#",  $desc['attributes'], $property);
			$property = str_replace("#EXTRA#",       $desc['extra'],      $property);
			$property = str_replace("#DEFAULT#",     $desc['default'],    $property);
			$property = str_replace("#NULL#",        $desc['null'],       $property);
			
			// The 'LENGTH' field is kind of screwy...
			$length = (gettype($desc['elements']) == 'array') ? "'" . implode("','", $desc['elements']) . "'" : $desc['length'];
			$property = str_replace("#LENGTH#", $length, $property);
			
			// Is this the primary key?
			if($desc['key'] == "PRI")
				$pKey = $column;
			
			// Done with this one
			$properties[] = $property;
			$longest = (strlen($column) > $longest) ? strlen($column) : $longest;
		}
		
		// Time to normalize the whitespace
		for($i=0; $i<count($properties); $i++)
		{
			$whitespace   = ($longest - strlen($columns[$i]) + 1);
			$wsformat     = "\${$columns[$i]};%{$whitespace}s";
			$propertyName = sprintf($wsformat, " ");
			$properties[$i] = str_replace("#PROPERTY NAME#", $propertyName, $properties[$i]);
		}
		
		// Lump the properties into one gigantic string
		$properties = implode("", $properties);
		
		// Replace everything in the template
		$contents = str_replace("#CLASS NAME#",  $className,  $class    );
		$contents = str_replace("#FILE NAME#",   $fileName,   $contents );
		$contents = str_replace("#TABLE NAME#",  $table,      $contents );
		$contents = str_replace("#DATE#",        $date,       $contents );
		$contents = str_replace("#PRIMARY KEY#", $pKey,       $contents );
		$contents = str_replace("#PROPERTIES#",  $properties, $contents );
		
		// Write the file
		if(false !== @file_put_contents($folder . $fileName, $contents))
			echo "<span class=\"success\">Success!</span>";
		else
			echo "<span class=\"fail\">Failed!</span>";
		
		echo "</p>\n";
	}
}
?>

  </div>
</div>

</body>
</html>
